/**
 * @Author:周邱艳
 * @Date:20200617
 * @Describle:这是组合列表页
 */
import {
    Card,
    Button,
    Table,
    Input,
    Space, message,Modal,Popconfirm,
} from 'antd'
import React, { Component } from "react";
import axios from "axios"
import Highlighter from 'react-highlight-words';
import { SearchOutlined } from '@ant-design/icons';
import {URL} from '../../../index'
import {BrowserRouter as Router, Route, Link} from 'react-router-dom'
import {getCookieId} from "../../../utils/GetCookie";

var disableUp = false
export default class PortfolioListTable extends Component {

    //初始化table的所有列信息的数组
    constructor(props) {
        super(props);
        this.state={
            combinationBaseInfoDtoList:[],//所有分类的数组
            loading:false,//是否正在请求加载中
            searchText: '',//搜索内容
            searchedColumn: '',//搜索列表
            upDisable:false,
            downDisable:false,
            visible:false,
        }
        //数据绑定
        this.getCategorys=this.getCategorys.bind(this)

    }
    //加载列表
    initColumns = () =>{
        console.log(getCookieId())
        this.columns = [
            {
                title: '组合代码',
                dataIndex: 'comBaseCode',
                ...this.getColumnSearchProps('comBaseCode'),
            },
            {
                title: '组合名称',
                dataIndex: 'comBaseName',
                ...this.getColumnSearchProps('comBaseName'),

            },
            {
                title: '组合起购金额',
                dataIndex: 'conBaseStartMoney',
                ...this.getColumnSearchProps('conBaseStartMoney'),
            },
            {
                title: '组合产品类别',
                dataIndex: 'comBaseCate',
                ...this.getColumnSearchProps('comBaseCate'),
            },
            {
                title: '组合风险等级',
                dataIndex: 'comBaseRiskLevel',
                ...this.getColumnSearchProps('comBaseRiskLevel'),
            },
            {
                title: '组合状态',
                dataIndex: 'comBaseStatus',
                ...this.getColumnSearchProps('comBaseStatus'),
            },
            {
                title: '组合创建时间',
                dataIndex: 'gmtCreate',
                ...this.getColumnSearchProps('gmtCreate'),
            },

            {
                title: '操作1',
                render:(record) =>(
                    (record.counselorId === getCookieId() || record.comBaseStatus !== "已创建")?(
                        <Button disabled={true} type="primary">上架</Button>
                    ):(
                        <Popconfirm title="是否确认上架?" onConfirm={(e) => this.upMarket(record,e)}>
                            <Button id={record.comBaseId}  type="primary">上架</Button>
                        </Popconfirm>
                    )
                )
            },
            {
                title: '操作2',
                render:(record) =>(
                    (record.counselorId === getCookieId() || record.comBaseStatus !== "已上架")?(
                        <Button disabled={true} type="primary" danger>
                            下架
                        </Button>
                    ):(
                        <Popconfirm title="是否确认下架?" onConfirm={(e) => this.downMarket(record,e)}>
                            <Button id={record.comBaseId}  type="primary" danger>
                                下架
                            </Button>
                        </Popconfirm>
                    )
                )
            },
            {
                title: '操作3',
                render:(record) =>(
                    <Button type="primary" >
                        <Router>
                            <Link to={"/portfolioDetail"} onClick={()=>{this.props.func(record.comBaseId)}}>
                                组合详情
                            </Link>
                        </Router>
                    </Button>
                )
            },
        ];
    }
    handleCancelUp = e => {
        this.setState({
            visible: false,
        });
    };
    //上架函数
    upMarket(record,e){
        if(e.currentTarget.disabled === false){
            //数据请求
            axios({
                method:"GET",
                url:URL+"/combinationBaseInfo/combinationOnShelf",
                params:{comBaseId:record.comBaseId},
            }).then(res=>{
                //判断状态码
                if(res.data.code === 200){
                    message.success("上架成功！")
                    document.getElementById(record.comBaseId).disabled = true;
                    record.comBaseStatus = "已上架";
                    this.setState({})
                }
                //错误处理
            }).catch(error=>{
                console.log(error);
            });
        }
    }
    //下架函数
    downMarket(record,e){
        if(e.currentTarget.disabled === false){
            //数据请求
            axios({
                method:"GET",
                url:URL+"/combinationBaseInfo/combinationOutOffShelf",
                params:{comBaseId:record.comBaseId},
            }).then(res=>{
                //数据更新
                if(res.data.code === 200){
                    message.success("下架成功！")
                    document.getElementById(record.comBaseId).disabled = true;
                    record.comBaseStatus = "已下架";
                    this.setState({})
                }else if(res.data.code === 500){
                    this.props.history.push('/serverError')
                }
                //错误处理
            }).catch(error=>{
                console.log(error);
            });
        }
    }

    //异步获取分类列表显示
    getCategorys = () =>{
        //数据请求
        axios({
            method: "GET",
            url: URL + "/combinationBaseInfo/allcombinationBaseInfo",
            params: {}
        }).then(

            (res) => {
                //数据更新
                this.setState({
                    combinationBaseInfoDtoList: this.state.combinationBaseInfoDtoList.concat(res.data.combinationBaseInfoDtoList)
                })

            }
            //错误处理
        ).catch(function (error) {
            console.log(error);
        })
    }
    //组件挂载前
    componentWillMount() {
        this.initColumns()
    }
    //组件挂载后
    componentDidMount() {
        this.getCategorys()
    }
    //搜索函数
    getColumnSearchProps = dataIndex => ({
        filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
            <div style={{ padding: 8 }}>
                <Input
                    ref={node => {
                        this.searchInput = node;
                    }}
                    placeholder={`Search ${dataIndex}`}
                    value={selectedKeys[0]}
                    onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                    onPressEnter={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
                    style={{ width: 188, marginBottom: 8, display: 'block' }}
                />
                <Space>
                    {/*搜索按键*/}
                    <Button
                        type="primary"
                        onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
                        icon={<SearchOutlined />}
                        size="small"
                        style={{ width: 90 }}
                    >
                        Search
                    </Button>
                    {/*重置按键*/}
                    <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 90 }}>
                        Reset
                    </Button>
                </Space>
            </div>
        ),
        filterIcon: filtered => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />,
        onFilter: (value, record) =>
            record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownVisibleChange: visible => {
            if (visible) {
                setTimeout(() => this.searchInput.select());
            }
        },
        render: text =>
            this.state.searchedColumn === dataIndex ? (
                <Highlighter
                    highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
                    searchWords={[this.state.searchText]}
                    autoEscape
                    textToHighlight={text.toString()}
                />
            ) : (
                text
            ),
    });
    //搜索函数
    handleSearch = (selectedKeys, confirm, dataIndex) => {
        confirm();
        this.setState({
            searchText: selectedKeys[0],
            searchedColumn: dataIndex,
        });
    };
    //重置函数
    handleReset = clearFilters => {
        clearFilters();
        this.setState({ searchText: '' });
    };
    //数据渲染
    render() {
        //取出状态数据
        const {loading}=this.state

        return (
            <div>
                <Modal
                    title="上架确认"
                    visible={this.state.visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancelUp}
                >
                    <p>您是否确认上架该组合？</p>
                </Modal>
                <Card >
                    <Table
                        rowKey="comBaseId"
                        loading={loading}
                        columns={this.columns}
                        dataSource={this.state.combinationBaseInfoDtoList}
                        bordered={true}
                        pagination={{defaultPageSize:4,showQuickJumper:true}}
                    />
                </Card>
            </div>
        )
    }
}

